var util = require('../../utils/util.js')
const app = getApp()

Page({
  data: {
    categoryId: '',
    pId: '',
    selectPrice: 'zonghe',
    productList: [],
    current: 1,
    limit: 20,
    minPrice: 0,
    maxPrice: 0,
    pages: '', // 总页数
    keyword: '', //搜索关键词
    type: '', // 类型：IS_HOT：热销商品；IS_NEW：新品推荐
    order: '', // 排序字段 RETAIL_PRICE,SALES
    sortType: '', // 排序类型 ASC,DESC
    categoryAll: true, // 显示所有分类
    brandAll: true, // 显示所有品牌
    brandList: [],
    brandSelect: false, // 是否选中品牌
    brandIds: [],
    selectedBrandName: '品牌',
    categoryList: [],
    categorySelect: false, // 是否选中分类
    categoryIds: [],
    selectedCategoryName: '分类',
    searchStatus: 0,
    hot: [],
    history: [],
    showActionSheet: false,
    tips: '确认清空搜索历史吗？',
    width: 200, //header宽度
    height: 64, //header高度
    inputTop: 0, //搜索框距离顶部距离
    arrowTop: 0, //箭头距离顶部距离
    dropScreenH: 0, //下拉筛选框距顶部距离
    attrIndex: -1,
    dropBrandScreenShow: false,
    dropCategoryScreenShow: false,
    scrollTop: 0,
    tabIndex: 0, //顶部筛选索引
    isList: false, //是否以列表展示  | 列表或大图
    drawer: false,
    drawerH: 0, //抽屉内部scrollview高度
    selectedName: '综合',
    selectH: 0
  },
  onLoad: function (options) {
    let that = this
    wx.setStorageSync('navUrl', '/pages/category/category')
    let obj = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: res => {
        that.setData({
          width: obj.left || res.windowWidth,
          height: obj.top ? obj.top + obj.height + 8 : res.statusBarHeight + 44,
          inputTop: obj.top ? obj.top + (obj.height - 30) / 2 : res.statusBarHeight + 7,
          arrowTop: obj.top ? obj.top + (obj.height - 32) / 2 : res.statusBarHeight + 6,
          dropScreenH: (that.data.height * 750) / res.windowWidth + 186,
          drawerH: res.windowHeight - 10 - that.data.height
        })
      }
    })
    // 页面初始化 options为页面跳转所带来的参数
    if (options.categoryId) {
      that.setData({
        categoryIds: [options.categoryId]
      })
    }
    if (options.brandId) {
      that.setData({
        brandIds: [options.brandId]
      })
    }
    if (options.keyword) {
      that.setData({
        keyword: options.keyword
      })
    }
    if (options.type) {
      that.setData({
        type: options.type
      })
    }
    if (options.showSearchHistory) {
      that.setData({
        searchStatus: 1
      })
    } else {
      that.setData({
        searchStatus: 2
      })
      that.getGoodsList()
    }
    that.getBrands()
    that.getCategorys()
    that.getHistory()
  },
  onPullDownRefresh: function () {
    this.setData({
      current: 1
    })
    this.getGoodsList()
    wx.stopPullDownRefresh()
  },
  onReachBottom: function () {
    if (this.current !== this.pages) {
      this.getGoodsList(true)
    }
  },
  openActionSheet: function () {
    this.setData({
      showActionSheet: true
    })
  },
  closeActionSheet: function () {
    this.setData({
      showActionSheet: false
    })
  },
  cleanHistory: function () {
    let that = this
    util.request('search/clearHistory', {}, 'POST').then(function (res) {
      that.setData({
        showActionSheet: false,
        history: []
      })
    })
  },
  getHistory () {
    let that = this
    util.request('search/history').then(function (res) {
      if (res.code === 0) {
        that.setData({
          hot: res.hotKeywordList,
          history: res.historyKeywordList
        })
      }
    })
  },
  inputChange: function (e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  clearKeyword: function () {
    this.setData({
      keyword: '',
      searchStatus: 1
    })
  },
  focusKeyword: function(){
    this.setData({
      searchStatus: 1
    })
  },
  resetAll () {
    this.setData({
      minPrice: 0,
      maxPrice: 0
    })
    this.resetBrand()
    this.resetCategory()
  },
  checkPrice (type) {
    if (type === 1) {
      this.setData({
        minPrice: util.replaceAll(util.rmoney(this.data.minPrice), ',', '')
      })
    } else {
      this.setData({
        maxPrice: util.replaceAll(util.rmoney(this.data.maxPrice), ',', '')
      })
    }

  },
  resetBrand () {
    this.setData({
      brandIds: [],
      brandSelect: false,
      selectedBrandName: '品牌'
    })
    this.getBrands()
  },
  getBrands: function () {
    let that = this
    util.request('brand/brandAll').then(function (res) {
      if (res.code === 0) {
        that.setData({
          brandList: res.data
        })
        if (that.data.brandIds.length > 0) {
          let attrName = ''
          let active = false
          for (let brand of that.data.brandList) {
            brand.selected = false
            for (let brandId of that.data.brandIds) {
              if (brand.id === brandId) {
                active = true
                brand.selected = true
                attrName += attrName ? ';' + brand.name : brand.name
              }
            }
          }
          that.setData({
            brandList: that.data.brandList,
            brandSelect: active,
            selectedBrandName: attrName || '品牌'
          })
        }
      }
    })
  },
  resetCategory () {
    this.setData({
      categoryIds: [],
      categorySelect: false,
      selectedCategoryName: '分类'
    })
    this.getCategorys()
  },
  getCategorys: function () {
    let that = this
    util.request('category/categoryList', {
      level: 2
    }).then(function (res) {
      if (res.code === 0) {
        that.setData({
          categoryList: res.data
        })
        if (that.data.categoryIds.length > 0) {
          let attrName = ''
          let active = false
          for (let category of that.data.categoryList) {
            category.selected = false
            for (let categoryId of that.data.categoryIds) {
              if (category.id === categoryId) {
                active = true
                category.selected = true
                attrName += attrName ? ';' + category.name : category.name
              }
            }
          }
          that.setData({
            categoryList: that.data.categoryList,
            categorySelect: active,
            selectedCategoryName: attrName || '分类'
          })
        }
      }
    })
  },
  getGoodsList: function (reachBottom) {
    let that = this
    let loadData
    if (reachBottom) {
      loadData = JSON.parse(JSON.stringify(that.data.productList))
      that.setData({
        current: that.data.current + 1
      })
    }
    util.request('search/seachList', {
      type: that.data.type,
      keyword: that.data.keyword,
      searchFrom: 1,
      categoryIds: that.data.categoryIds.join(','),
      current: that.data.current,
      limit: that.data.limit,
      order: that.data.order,
      sortType: that.data.sortType,
      brandIds: that.data.brandIds.join(','),
      minPrice: that.data.minPrice,
      maxPrice: that.data.maxPrice
    }).then(function (res) {
      if (res.code === 0) {
        that.setData({
          searchStatus: 2,
          productList: res.data.records,
          pages: res.data.pages
        })
        if (reachBottom) {
          that.setData({
            productList: loadData.concat(res.data.records)
          })
        }
      }
    })
  },
  newSelectSerach () {
    let that = this
    if (that.data.type === 'IS_NEW') {
      that.setData({
        type: ''
      })
    } else {
      that.setData({
        type: 'IS_NEW'
      })
    }
    that.getGoodsList()
  },
  brandSelectSerach () {
    let that = this
    that.setData({
      attrIndex: 1,
      dropCategoryScreenShow: false
    })
    if (that.data.brandList.length === 0) {
      that.btnBrandCloseDrop()
    } else {
      that.setData({
        scrollTop: 1,
        dropBrandScreenShow: true
      })
    }
  },
  categorySelectSerach () {
    let that = this
    that.setData({
      attrIndex: 2,
      dropBrandScreenShow: false
    })
    if (that.data.categoryList.length === 0) {
      that.btnCategoryCloseDrop()
    } else {
      that.setData({
        scrollTop: 1,
        dropCategoryScreenShow: true
      })
    }
  },
  onKeywordConfirm () {
    let that = this
    that.setData({
      current: 1,
      order: '',
      sortType: '',
      productList: []
    })
    that.getGoodsList()
  },
  onKeywordTap: function (e) {
    let url =  e.currentTarget.dataset.item.SCHEME_URL, keyword = e.currentTarget.dataset.item.KEYWORD
    let that = this
    if (url) {
      wx.navigateTo({
        url: url
      })
    } else {
      that.setData({
        keyword: keyword,
      })
      this.onKeywordConfirm()
    }
  },
  selectPriceTap: function (e) {
    let that = this
    let selectPrice = e.currentTarget.dataset.type
    that.setData({
      selectPrice: selectPrice,
      selectedName: selectPrice === 'zonghe' ? '综合' : '价格',
      selectH: 0,
      current: 1
    })
    if (selectPrice === 'zonghe') {
      that.setData({
        order: '',
        sortType: ''
      })
      that.getGoodsList()
    } else {
      that.setData({
        order: 'SALES',
        sortType: selectPrice
      })
      that.getGoodsList()
    }
  },
  goodsDetail: function (event) {
    let goodsId = event.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/goods/goods?id=' + goodsId,
    })
  },
  px (num) {
    return num / 2 + 'px'
  },
  screen: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    that.hideDropdownList()
    that.btnBrandCloseDrop()
    that.btnCategoryCloseDrop()
    if (index == 0) {
      that.showDropdownList()
    } else if (index == 1) {
      that.setData({
        tabIndex: 1,
        current: 1,
        order: 'SALES',
        sortType: 'DESC'
      })
      that.getGoodsList()
    } else if (index == 2) {
      that.setData({
        isList: !that.data.isList
      })
    } else if (index == 3) {
      that.setData({
        drawer: true
      })
    }
  },
  showDropdownList: function () {
    this.setData({
      selectH: 246,
      tabIndex: 0
    })
  },
  hideDropdownList: function () {
    this.setData({
      selectH: 0
    })
  },
  closeDrawer: function () {
    this.setData({
      drawer: false
    })
    this.getGoodsList()
  },
  back: function () {
    if (this.data.searchStatus == 1) {
      this.setData({
        searchStatus: 2
      })
    } else if (this.drawer) {
      this.closeDrawer()
    } else {
      wx.navigateBack({
        fail () {
          wx.switchTab({
            url: '/pages/index/index'
          })
        }
      })
    }
  },
  brandSelected: function (e) {
    let index = e.currentTarget.dataset.index
    this.data.brandList[index].selected = !this.data.brandList[index].selected
    this.setData({
      brandList: this.data.brandList
    })
  },
  brandAllChange: function () {
    this.setData({
      brandAll: !this.data.brandAll
    })
  },
  categorySelected: function (e) {
    let index = e.currentTarget.dataset.index
    this.data.categoryList[index].selected = !this.data.categoryList[index].selected
    this.setData({
      categoryList: this.data.categoryList
    })
  },
  categoryAllChange: function () {
    this.setData({
      categoryAll: !this.data.categoryAll
    })
  },
  brandSelectedSure: function () {
    let that = this
    let arr = that.data.brandList
    let active = false
    let attrName = ''
    let brandIds = []
    //这里只是为了展示选中效果,并非实际场景
    for (let item of arr) {
      if (item.selected) {
        active = true
        attrName += attrName ? ';' + item.name : item.name
        brandIds.push(item.id)
      }
    }
    that.btnBrandCloseDrop()

    that.setData({
      brandIds: brandIds,
      brandSelect: active,
      selectedBrandName: attrName || '品牌',
      current: 1
    })
    that.getGoodsList()
  },
  categorySelectedSure: function () {
    let that = this
    let arr = that.data.categoryList
    let active = false
    let attrName = ''
    let categoryIds = []
    //这里只是为了展示选中效果,并非实际场景
    for (let item of arr) {
      if (item.selected) {
        active = true
        attrName += attrName ? ';' + item.name : item.name
        categoryIds.push(item.id)
      }
    }
    that.btnCategoryCloseDrop()

    that.setData({
      categoryIds: categoryIds,
      categorySelect: active,
      selectedCategoryName: attrName || '分类',
      current: 1
    })
    that.getGoodsList()
  },
  btnBrandCloseDrop () {
    this.setData({
      scrollTop: 1
    })
    this.setData({
      dropBrandScreenShow: false,
      attrIndex: -1
    })
  },
  btnCategoryCloseDrop () {
    this.setData({
      scrollTop: 1
    })
    this.setData({
      dropCategoryScreenShow: false,
      attrIndex: -1
    })
  }
})
